<?php ob_start(); ?>
<?php
$pageTitle = "复习";
$currentPage = "review";
include('../resource/db/db.php');
include('../resource/navbar.php');
if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

if (!isset($_GET['box_number'])) {
    header("Location: ../main/user-index.php");
    exit();
}

$boxNumber = $_GET['box_number']; // 获取传递的盒子编号
$user_id = $_COOKIE['user_id'];
$record_id = $_GET['record_id'];

$boxNames = [
    1 => '今天',
    2 => '明天',
    3 => '一周后',
    4 => '十四天后',
    5 => '一个月后',
    6 => '永恒'
];


$sql = "SELECT * FROM study_records JOIN cards ON study_records.card_id = cards.card_id AND study_records.set_id = cards.set_id
WHERE study_records.record_id='$record_id' AND study_records.user_id='$user_id' AND study_records.is_deleted=FALSE AND study_records.box_number='$boxNumber'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_cnt = $conn->query("SELECT COUNT(*) as count FROM study_records WHERE user_id='$user_id' AND box_number='$boxNumber' AND is_deleted=FALSE");
$total_cnt = $total_cnt->fetch_assoc()['count'];

function getNextReviewDate($currentBoxNumber)
{
    switch ($currentBoxNumber) {
        case 1:
            return date('Y-m-d H:i:s', strtotime("+1 day"));
        case 2:
            return date('Y-m-d H:i:s', strtotime("+3 days"));
        case 3:
            return date('Y-m-d H:i:s', strtotime("+7 days"));
        case 4:
            return date('Y-m-d H:i:s', strtotime("+14 days"));
        case 5:
            return date('Y-m-d H:i:s', strtotime("+30 days"));
        default:
            return date('Y-m-d H:i:s', strtotime("+1 day"));
    }
}
?>

<!DOCTYPE html>
<html>

<head>
    <title><?php echo $pageTitle; ?></title>
    <link rel="stylesheet" href="../resource/css/styles.css">
    <style>
        .card-container {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin-bottom: 20px;
        }

        .card {
            width: 300px;
            height: 500px;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 20px;
            cursor: pointer;
        }

        .card-back {
            display: none;
        }

        .page-change {
            display: flex;
            flex-direction: row;
        }

        .previous-page {
            margin-right: 25px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2><?php echo $boxNames[$boxNumber]?>复习页面：</h2>
        <h3>点击卡片切换正反面</h3>
        <?php
        // 返回上一级链接
        echo "<a href='../main/user-index.php'>返回首页</a>";
        if ($row) {
            // 显示当前复习的是箱子里的第几张卡片
            $current_record_sql = "SELECT COUNT(*) as count FROM study_records 
            WHERE user_id='$user_id' AND box_number='$boxNumber' AND record_id <= '{$row['record_id']}' AND is_deleted=FALSE";
            $current_record_result = $conn->query($current_record_sql);
            $current_record_row = $current_record_result->fetch_assoc();
            echo "<div class='card-container'>";
            echo "<div class='card' onclick='flipCard()'>";
            echo "<div class='card-front'>" . $row['title'] . "</div>";
            echo "<div class='card-back' style='display:none'>" . $row['content'] . "</div>";

            // 翻面
            echo "<script>";
            echo "var cardFront = document.querySelector('.card-front');";
            echo "var cardBack = document.querySelector('.card-back');";
            echo "function flipCard() {";
            echo "cardFront.style.display = (cardFront.style.display === 'none') ? 'block' : 'none';";
            echo "cardBack.style.display = (cardBack.style.display === 'none') ? 'block' : 'none';";
            echo "}";
            echo "</script>";
        ?>
    </div>
    <div style="padding-top:20px; padding-bottom:20px">
        <?php
        echo "<form method='post' action=''>";
        echo "<input type='hidden' name='record_id' value='{$row['record_id']}'>";
        echo "<input type='submit' name='reviewed' value='复习完成'>";
        echo "</form>";
        ?>
    </div>
    <div class="page-change">
        <div class="previous-page">
            <?php
            // 查询上一张卡片
            $prev_sql = "SELECT record_id FROM study_records 
            WHERE user_id='$user_id' AND box_number='$boxNumber' AND record_id < '{$row['record_id']}' AND is_deleted=FALSE 
            ORDER BY record_id DESC LIMIT 1";
            $prev_result = $conn->query($prev_sql);
            if ($prev_result->num_rows > 0) {
                $prev_row = $prev_result->fetch_assoc();
                echo "<a href='review.php?box_number=$boxNumber&record_id={$prev_row['record_id']}'>查看上一张卡片</a>";
            }
            ?>
        </div>
        <div class="next-page">
            <?php
            // 查询下一张卡片
            $next_sql = "SELECT record_id FROM study_records 
            WHERE user_id='$user_id' AND box_number='$boxNumber' 
            AND record_id > '{$row['record_id']}' AND is_deleted=FALSE ORDER BY record_id LIMIT 1";
            $next_result = $conn->query($next_sql);
            if ($next_result->num_rows > 0) {
                $next_row = $next_result->fetch_assoc();
                echo "<a href='review.php?box_number=$boxNumber&record_id={$next_row['record_id']}'>查看下一张卡片</a>";
            }
            ?>
        </div>

    </div>
    <?php
            echo "<p>当前复习的是箱子里的第 " . $current_record_row['count'] . "/" . $total_cnt . " 张卡片</p>";
    ?>
    <?php
            $next_sql = "SELECT record_id FROM study_records WHERE user_id='$user_id' AND box_number='$boxNumber' AND record_id > '{$row['record_id']}' AND is_deleted=FALSE ORDER BY record_id LIMIT 1";
            $next_result = $conn->query($next_sql);
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reviewed'])) {
                $boxNumber = $row['box_number'] + 1;
                $next_review = getNextReviewDate($boxNumber);
                $sql_update = "UPDATE study_records SET last_reviewed=NOW(), next_review='$next_review', box_number='$boxNumber' WHERE record_id='{$row['record_id']}'";
                if ($conn->query($sql_update) === TRUE) {
                    echo "复习记录更新成功";
                    // 跳转到下一张卡片
                    $boxNumber -= 1;
                    $next_sql = "SELECT record_id FROM study_records WHERE user_id='$user_id' AND box_number='$boxNumber' AND record_id > '{$row['record_id']}' AND is_deleted=FALSE ORDER BY record_id LIMIT 1";
                    $next_result = $conn->query($next_sql);
                    if ($next_result->num_rows > 0) {
                        $next_row = $next_result->fetch_assoc();
                        header("Location: review.php?box_number=$boxNumber&record_id={$next_row['record_id']}");
                        ob_end_flush();
                        exit();
                    } else {
                        header("Location: review.php?box_number=$boxNumber");
                        ob_end_flush();
                        exit();
                    }

                } else {
                    echo "Error: " . $sql_update . "<br>" . $conn->error;
                }
            }
    ?>
<?php
        } else {
            echo "<p>该盒子中暂时没有卡片哦~</p>";
        }
?>
</div>
</body>

</html>
